package com.bobbygu.server.simpleapp.controller;

import com.bobbygu.server.simpleapp.mapper.UploadMapper;
import com.bobbygu.server.simpleapp.model.ImgModel;
import com.bobbygu.server.simpleapp.model.response.BaseResponse;
import com.bobbygu.server.simpleapp.model.response.ConstResponse;
import com.bobbygu.server.simpleapp.model.response.ResultResponse;
import com.bobbygu.server.simpleapp.model.response.StringResponse;
import com.bobbygu.server.simpleapp.utils.FileUtils;
import com.bobbygu.server.simpleapp.utils.SafeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
public class UploadController {
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private UploadMapper uploadMapper;

    @RequestMapping(value = "/home/upload", method = RequestMethod.POST)
    public BaseResponse upload(MultipartHttpServletRequest multiReq) throws IOException, ServletException {
        System.out.println("upload");
        final String imgName = "ImgData";
        String rootPath = multiReq.getSession().getServletContext().getRealPath("/");
        final String ROOT = rootPath + "imageDir";

        FileInputStream fs = (FileInputStream) multiReq.getPart(imgName).getInputStream();

        String token = SafeUtil.MD5("app" + fs);
        ImgModel imgModel = uploadMapper.findImgByName(imgName);
        try {
            Path path = Paths.get(ROOT, imgName + ".jpg");
            System.out.println(ROOT);
            System.out.println(path.toAbsolutePath().toString());
            if (!path.toFile().exists())
                FileUtils.createFile(path.toString());
            Files.delete(path);
            Files.copy(fs, path);
            System.out.println(" Files.copy success!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(" Files.copy fail!");
        }
        if (imgModel != null) {
            uploadMapper.updateImg(imgName, ROOT, fs, token);
        } else {
            uploadMapper.insertImg(imgName, ROOT, fs, token);
        }

        return new ResultResponse(new StringResponse("上传成功"), ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
    }

    @RequestMapping(value = "/home/getImg.do", method = RequestMethod.POST)
    public ResponseEntity<InputStreamResource> getImg(@RequestBody Map<String, Object> requestMap) throws IOException {
        System.out.println("getImg.do");

        String name = requestMap.get("Name").toString();
        ImgModel imgModel = uploadMapper.findImgByName(name);

        String filePath = imgModel.imgurl + "/" + imgModel.name + ".jpg";
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
